<template>
  <view class="container">
    <div class="fee-pane-content">
      <ve-form class="fee-pane-item" :model="feeForm" ref="feeFormRef" :rules="rules" layout="vertical" v-if="feeForm.orderFee.length > 0">
        <ve-card v-for="(item, index) in feeForm.orderFee" :key="index">
          <div class="order-fee-item">
            <div class="order-fee-item-content">
              <fee-pane
                :orderFeeIndex="index"
                :showStatistic="false"
                :showFeeItemTitle="false"
                :inlineCard="true"
                :disabledOnlineFee="true"
              >
                <template #feePaneHeaderFeeName>
                  <!-- 切换费用名称 -->
                  <ve-form-item
                    :prop="`orderFee.${index}.feeDetailType`"
                    required
                    label="费用名称"
                    :borderBottom="item.feeDetailList?.length > 0"
                  >
                    <ve-picker-inline
                      v-model="item.feeDetailType"
                      placeholder="请选择"
                      :range="orderFeeCategoryEnum"
                      unit="arrowRight"
                      @change="(val) => changeFeeTypeFn(val, item)"
                    />
                  </ve-form-item>
                </template>
              </fee-pane>
              <ve-button class="delete-button" type="plain" status="danger" v-if="index > 0" @click="delFeeFn(index)">
                <template #icon>
                  <ve-icon name="delete" width="36" height="36" />
                </template>
                删除此费用
              </ve-button>
            </div>
          </div>
        </ve-card>
      </ve-form>
      <ve-button type="plain" @click="addFeeFn" :customStyle="{ backgroundColor: '#F3F7FF' }">
        <template #icon>
          <ve-icon name="plus" width="36" height="36" />
        </template>
        添加费用
      </ve-button>
    </div>
    <!-- 底部 footer -->
    <footer-box id="footer-box">
      <template #extra>
        <feeStatistic />
      </template>
      <ve-button type="primary" size="long" :loading="okLoading" @click="submitFn">确认</ve-button>
    </footer-box>
  </view>
</template>
<script setup>
  import { ref, computed, provide } from 'vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import footerBox from './form/components/footerBox.vue'
  import feeStatistic from './components/order-fee/fee-statistic.vue'
  import { getOrdrDetailsAPI, addOrderCostAPI } from '@/api/order/lOrder'
  import {
    buildCostInfoParam,
    getStoreTemplateDetail,
    compileFeeItemFromTemplate,
    initFeeDetail,
  } from './components/order-fee/fee-utils.js'
  import { cloneDeep } from '@/utils/index'
  import useFormFold from '@/hooks/useFormFold'
  const { foldValidate } = useFormFold([])
  import { onLoad } from '@dcloudio/uni-app'
  import useToast from '@/hooks/useToast'

  // 门店模板信息
  const storeTemplate = ref()
  // 短租模板Id
  const priceTemplateId = ref()

  const orderInfo = ref({})
  const orderId = ref()
  const workOrderId = ref()
  // 费用相关 开始
  const feeFormRef = ref()
  const feeForm = ref({
    id: 0,
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        readTemplate: true,
        feeDetailType: undefined,
        feeDetailList: [],
        feeDetailTypeList: [],
      },
    ],
  })
  provide('feeForm', feeForm)
  onLoad((options) => {
    orderId.value = options.id
    feeForm.value.id = options.id
    // 读取订单信息
    getOrdrDetailsAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (template, templateId) => {
        storeTemplate.value = template
        priceTemplateId.value = templateId
        // 如果在未读取成功前，进行了 addFeeFn 及 changeFeeTypeFn 操作，需要补一下数据
        let orderFee = feeForm.value.orderFee
        if (orderFee && orderFee.length > 0) {
          if (orderFee.some((item) => item.feeDetailTypeList.length > 0)) {
            initFeeDetail(feeForm.value, storeTemplate.value)
          }
        }
      })
    })
    if (options.workOrderId) {
      workOrderId.value = options.workOrderId
    }
  })

  // 获取门店配置开始
  const changeFeeTypeFn = (val, item) => {
    item.feeDetailTypeList = [val]
    // 读取门店模板信息成功
    if (storeTemplate.value) {
      item.priceTemplateId = priceTemplateId.value
      let option = orderFeeCategoryEnum.value.find((orderFeeItem) => orderFeeItem.value == item.feeDetailType)
      item.feeNameId = option.feeNameId
      compileFeeItemFromTemplate(item, storeTemplate.value)
    }
  }
  // rules computed
  const rules = computed(() => {
    let _r = {}
    let orderFee = feeForm.value.orderFee
    orderFee.forEach((item, index) => {
      let propKey = `orderFee.${index}.feeDetailType`
      _r[propKey] = {
        required: true,
        message: '请选择费用',
      }
    })
    return _r
  })
  // 添加费用可添加的费用类型集合
  const orderFeeCategoryEnum = computed(() => {
    let orderInfoVal = orderInfo.value
    if (orderInfoVal) {
      let status = orderInfoVal.status
      let allList = [
        { label: '增值服务费', value: 'addServiceFee', feeNameId: 8 },
        { label: '优惠费', value: 'preferentialFee', feeNameId: 11 },
        { label: '其他费用', value: 'otherFee', feeNameId: 4 },
        { label: '退款', value: 'refuseFee', feeNameId: 5 },
      ]
      // 用车中、已还车、已完成、已取消 可添加额外费用
      if ([200, 300, 1000, -100].includes(status)) {
        allList.splice(2, 0, { label: '额外费用', value: 'extraFee', feeNameId: 3 })
      }
      // 已取消仅可添加额外费用
      // if ([-100].includes(status)) {
      //   allList = [{ label: '额外费用', value: 'extraFee', feeNameId: 3 }]
      // }
      // 待用车、用车中、已还车、已完成、已取消
      // if ([100, 200, 300, 1000, -100].includes(status)) {
      //   allList.push({ label: '赔款', value: 'compensateFee', feeNameId: 17 })
      // }
      return allList
    } else {
      return []
    }
  })
  // 添加费用
  const addFeeFn = () => {
    feeForm.value.orderFee.push({
      // 费用类型（线上费用|线下费用）
      feeType: 1,
      readTemplate: true,
      feeDetailType: undefined,
      feeDetailList: [],
      feeDetailTypeList: [],
    })
  }
  // 删除费用
  const delFeeFn = (index) => {
    feeForm.value.orderFee.splice(index, 1)
  }
  // 对 orderFee 进行二次处理
  const handleOrderFee = (orderFee) => {
    let tempOrderFee = cloneDeep(orderFee)
    tempOrderFee.forEach((feeItem) => {
      let temp = []
      let feeDetailList = feeItem.feeDetailList
      let remark
      feeDetailList.forEach((feeDetailItem) => {
        let childrenList = feeDetailItem.childrenList
        childrenList.forEach((item) => {
          let tempObj = {
            feeCategory: feeDetailItem.feeCategory,
            type: 1,
            ...item,
          }
          if (feeDetailItem.compensateReason) {
            tempObj.compensateReason = feeDetailItem.compensateReason
          }
          temp.push(tempObj)
          remark = feeDetailItem.remark
        })
      })
      feeItem.remark = remark
      feeItem.feeDetailList = temp
    })
    return tempOrderFee
  }
  // 提交
  const okLoading = ref(false)
  const submitFn = () => {
    let feeFormValue = feeForm.value
    let { orderFee } = buildCostInfoParam(feeFormValue)
    const param = {
      id: feeFormValue.id,
      orderFeeList: handleOrderFee(orderFee),
    }
    if (workOrderId.value) {
      param.workOrderId = workOrderId.value
    }
    feeFormRef.value.validate((valid, errors) => {
      if (valid) {
        okLoading.value = true
        addOrderCostAPI(param)
          .then(() => {
            useToast({
              title: '添加费用成功',
            }).then(() => {
              uni.redirectTo({
                url: `/pages/order/long-order/detail/index?id=${orderId.value}&orderId=${orderId.value}&bizType=2&tab=expense`,
              })
            })
          })
          .catch(() => {
            okLoading.value = false
          })
      } else {
        foldValidate(errors, true)
      }
    })
  }
</script>
<style lang="less" scoped>
  .container {
    flex-direction: column;
    .fee-pane-content {
      flex: 1;
      overflow: auto;
      padding-bottom: 274rpx;
    }
    #footer-box {
      height: 250rpx;
      position: fixed;
      bottom: 0;
      background-color: #ffffff;
      z-index: 100;
    }
  }
  .fee-pane-content {
    padding: 24rpx;
  }
  .fee-pane-item {
    :deep(.ve-card-content) {
      padding-top: 2rpx;
      padding-bottom: 2rpx;
    }
  }
  .delete-button {
    margin-bottom: 30rpx;
  }
</style>
